package com.byxy.controller;


import com.byxy.po.Picture;
import com.byxy.service.FileService;
import com.byxy.util.FileUtil;
import com.byxy.util.RandomNum;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Controller
public class UpDownload {

    /**
     * 接受post方法，将表单传来的数据插入
     *
     * @param announce com.lingfei.admin.entity.Announce
     * @return 服务端跳转到announce.html
     */
    @Autowired
    private FileUtil fileService;
    @Autowired
    private FileService fileSer;

    @Value("${qiniu.path}")
    private String path;
    @Value("${baseUploadUrl}")
    private String url;

    /*@ApiOperation("插入数据")*/
    @PostMapping("/editormdPic")
    @ResponseBody
    public JSONObject editormdPic(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {


        String trueFileName = file.getOriginalFilename();
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        String fileName = session.getAttribute("account") + "_" + RandomNum.getDateTime() + System.currentTimeMillis() + suffix;
        String destFileName = request.getServletContext().getRealPath("") + "uploaded/" + fileName + File.separator;
        File targetFile = new File(url + destFileName);
        targetFile.getParentFile().mkdirs();

        file.transferTo(targetFile);
        Map response = fileService.uploadFile(targetFile, fileName);
        String urls = fileService.getUploadToken();
        Object imageName = response.get("imgName");
        System.out.println(urls);

       /* JSONObject jsonObject=new JSONObject ();
        jsonObject.put("url", imageName);
        jsonObject.put("success",1);
        jsonObject.put("message","upload success!");
           *//* DefaultPutRet putRet = new Gson().fromJson(map.bodyString(), DefaultPutRet.class);
            announce.setPicture(putRet.key);//这个就是从七牛云获取的文件名*/

        JSONObject json = new JSONObject();
        json.put("url", path + imageName);
        json.put("success", 1);
        json.put("message", "upload success!");
        Picture picture = new Picture();
        Integer account= (Integer)session.getAttribute("account");
        picture.setPicture_url(fileName);
        picture.setPicture_time(new Date());
        picture.setUserId(account);
        fileSer.insert(picture);
        return json;
    }
}
